package com.mentalhealthplatform.global.debounce;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;

import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class DebounceAspect {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Around("@annotation(debounce)")
    public Object debounce(ProceedingJoinPoint joinPoint, Debounce debounce) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String clientIp = request.getRemoteAddr();
        String endpoint = request.getRequestURI();

        long interval = debounce.interval();
        String debounceKey = "debounce:" + clientIp + ":" + endpoint;

        // 使用 setIfAbsent 来确保键仅在首次请求时存在
        Boolean isFirstRequest = redisTemplate.opsForValue().setIfAbsent(debounceKey, "1", interval, TimeUnit.MILLISECONDS);

        if (Boolean.TRUE.equals(isFirstRequest)) {
            // 如果是第一个请求，则立即执行操作并返回结果
            return joinPoint.proceed();
        } else {
            // 如果键已经存在，则延长过期时间，表示重新计时
            redisTemplate.expire(debounceKey, interval, TimeUnit.MILLISECONDS);
            // 返回 null 表示不执行任何操作，前端可以根据此情况处理
            return null;
        }
    }
}
